#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>

int main(int argc, const char **argv) {
  int fd[2];
  int ret;
  ret = pipe(fd);
  if (ret < 0) {
    perror("pipe fail");
    exit(-1);
  }

  pid_t pid;
  pid = fork();

  if (pid > 0) {
    int i;
    char w_buf[1024];
    char r_buf[1024];
    for (i = 1; i < 20; i++) {
      bzero(w_buf, 1024);
      sprintf(w_buf, "%s %d", "This is father ", i);
      ret = write(fd[1], w_buf, strlen(w_buf));
      sleep(i);

      bzero(r_buf, 1024);
      ret = read(fd[0], r_buf, 1024);
      printf("I am father,I read is %s\n", r_buf);
      sleep(i);
    }
  } else if (pid == 0) {
    int i;
    char w_buf[1024];
    char r_buf[1024];
    for (i = 1; 20; i++) {
      bzero(r_buf, 1024);
      ret = read(fd[0], r_buf, 1024);
      printf("I am child,I read is %s\n", r_buf);
      sleep(i+1);

      bzero(w_buf, 1024);
      sprintf(w_buf, "%s %d", "This is child ", i);
      ret = write(fd[1], w_buf, strlen(w_buf));
      sleep(i+1);

    }
  }

  return 0;
}
